<template>
  <div class="update-avatar">
    <img fit="cover" :src="photo" ref="img" />
    <div class="toolbar">
      <span @click="$emit('close')">取消</span>
      <span @click="confirm">完成</span>
    </div>
  </div>
</template>

<script>
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
import { updateUserAvatar } from '@/api/user.js'
export default {
  props: ['photo'],
  mounted() {
    const image = this.$refs.img
    this.cropper = new Cropper(image, {
      viewMode: 1, // 只能在裁剪的图片范围内移动
      dragMode: 'move', // 画布和图片都可以移动
      aspectRatio: 1, // 裁剪区默认正方形
      autoCropArea: 1, // 自动调整裁剪图片
      cropBoxMovable: false, // 禁止裁剪区移动
      cropBoxResizable: false, // 禁止裁剪区缩放
      background: false, // 关闭默认背景
    })
  },
  methods: {
    // 点击完成
    confirm() {
      this.cropper.getCroppedCanvas().toBlob(async blob => {
        this.$toast.loading({
          message: '上传图片中...',
          duration: 0,
        })

        try {
          //创建一个formdata 实例
          const formdata = new FormData()
          // 拼接
          formdata.append('photo', blob)
          // 以后只要设计到图片上传, 立马脑子里面想到的是 formdata
          let res = await updateUserAvatar(formdata)
          console.log(res.data)
          this.$toast.success('上传成功')
          // 关闭
          this.$emit('close')
          // 传递数据
          this.$emit('update:photo', res.data.data.photo)
        } catch (error) {
          this.$toast.fail('上传失败')
        }
      })
    },
  },
}
</script>

<style scoped lang="less">
.update-avatar {
  background: #000;
  width: 100%;
  height: 100%;
  .toolbar {
    position: fixed;
    bottom: 10px;
    width: 100%;
    display: flex;
    justify-content: space-between;
    font-size: 28px;
    color: #fff;
    padding: 0 15px;
    box-sizing: border-box;
  }
}

// img {
//   width: 100%;
// }
</style>
